import json

from django import http

from django.core.paginator import EmptyPage, Paginator
from django.db.models.sql import constants
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from apps.contents.utils import get_categories
from apps.goods.models import GoodsCategory, SKU, GoodsVisitCount
from apps.goods.utils import get_breadcrumb, get_hots
from apps.orders.models import OrderGoods
from utils.response_code import RETCODE


class ListView(View):
    """商品列表页"""

    def get(self, request, category_id, page_num):
        """提供商品列表页"""
        sort=request.GET.get('sort')
        try:
            category=GoodsCategory.objects.get(id=category_id)
        except:
            return http.HttpResponseNotFound('GoodsCategory does not exist')
        breadcrumb=get_breadcrumb(category)
        categories=get_categories()


        # 按照排序规则查询该分类商品SKU信息
        if sort == 'price':
            # 按照价格由低到高
            sort_field = 'price'
        elif sort == 'hot':
            # 按照销量由高到低
            sort_field = '-sales'
        else:
            # 'price'和'sales'以外的所有排序方式都归为'default'
            sort_field = 'create_time'
        skus = SKU.objects.filter(category=category, is_launched=True).order_by(sort_field)
        print(skus)
        # 创建分页器：每页N条记录
        paginator = Paginator(skus, 5)
        # 获取每页商品数据
        try:
            page_skus = paginator.page(page_num)

        except EmptyPage:
            # 如果page_num不正确，默认给用户404
            return http.HttpResponseNotFound('empty page')
        # 获取列表页总页数
        total_page = paginator.num_pages
        context = {
            'categories': categories,  # 频道分类
            'breadcrumb': breadcrumb,  # 面包屑导航
            'sort': sort,  # 排序字段
            'category': category,  # 第三级分类
            'page_skus': page_skus,  # 分页后数据
            'total_page': total_page,  # 总页数
            'page_num': page_num,  # 当前页码
        }
        return render(request, 'list.html',context)

#热销排行
class HotGoodsView(View):
    def get(self,request,category_id):

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'hot_skus': get_hots(category_id)})


class DetailView(View):
    def get(self,request,sku_id):
        try:
            sku=SKU.objects.get(id=sku_id)
        except:
             return   render(request,'404.html')

        categories=get_categories()
        breadcrumb=get_breadcrumb(sku.category)
        hot_skus=get_hots(sku_id)
        # 构建当前商品的规格键
        sku_specs = sku.specs.order_by('spec_id')
        sku_key = []
        for spec in sku_specs:
            sku_key.append(spec.option.id)
        # 获取当前商品的所有SKU
        skus = sku.spu.sku_set.all()
        # 构建不同规格参数（选项）的sku字典
        spec_sku_map = {}
        for s in skus:
            # 获取sku的规格参数
            s_specs = s.specs.order_by('spec_id')
            # 用于形成规格参数-sku字典的键
            key = []
            for spec in s_specs:
                key.append(spec.option.id)
            # 向规格参数-sku字典添加记录
            spec_sku_map[tuple(key)] = s.id
        # 获取当前商品的规格信息
        goods_specs = sku.spu.specs.order_by('id')
        # 若当前sku的规格信息不完整，则不再继续
        if len(sku_key) < len(goods_specs):
            return
        for index, spec in enumerate(goods_specs):
            # 复制当前sku的规格键
            key = sku_key[:]
            # 该规格的选项
            spec_options = spec.options.all()
            for option in spec_options:
                # 在规格参数sku字典中查找符合当前规格的sku
                key[index] = option.id
                option.sku_id = spec_sku_map.get(tuple(key))
            spec.spec_options = spec_options
        context={
            'categories':categories,
            'hot_skus':hot_skus,
            'sku':sku,
            'breadcrumb':breadcrumb,
            'specs': goods_specs,

        }

        return render(request,'detail.html',context)

class DetailVisitView(View):
    def post(self,request,category_id):
        try:
            cat3=GoodsCategory.objects.get(id=category_id)
        except:
            return http.HttpResponseForbidden('不存在该商品')

        from datetime import datetime
        # 将日期按照格式转换成字符串
        today_str = datetime.now().strftime('%Y-%m-%d')
        # 将字符串再转换成日期格式
        today_date = datetime.strptime(today_str, '%Y-%m-%d')
        #如
        try:
            visit=GoodsVisitCount.objects.get(date=today_date,category_id=category_id)
            visit.count+=1
            visit.save()
        except:
            visit=GoodsVisitCount()
            visit.category_id=category_id
            visit.date=today_date
            visit.count=1
            visit.save()
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})


class CommentsView(View):
    def get(self,request,sku_id):
        """
                字段	说明
        code	状态码
        errmsg	错误信息
        comment_list[ ]	评价列表
        username	发表评价的用户
        comment	评价内容
        score	分数
        :param request:
        :return:
        """

        comment_list=[]

        goods=OrderGoods.objects.filter(sku_id=sku_id)
        print(goods)
        for good in goods:
            user=good.order.user
            comment_list.append({
                'username':user.username,
                'comment':good.comment,
                'scroe':good.score
            })


        return http.JsonResponse({
            "code":"0",
            "errmsg":"OK",
            "comment_list":comment_list
        })




